#include <stdio.h>
#include <utility>
#include <algorithm>

static char input[100][64];
static std::pair<int,int> keys[100]; /* inversion number => index */

int get_inversion_number(const char *s)
{
    int i, c, inv = 0;
    int count[4] = { 0 }; /* A, C, G, T */
    for (i = 0; c = s[i]; i++)
    {
        int k;
        switch (c)
        {
        case 'A': k = 0; break;
        case 'C': k = 1; break;
        case 'G': k = 2; break;
        case 'T': k = 3; break;
        default:  k = 0; break;
        }
        count[k]++;
        while (++k < 4)
            inv += count[k];
    }
    return inv;
}

int main()
{
    int len, num_input;
    scanf("%d %d", &len, &num_input);
    for (int i = 0; i < num_input; i++)
    {
        scanf("%s", input[i]);
        keys[i].first = get_inversion_number(input[i]);
        keys[i].second = i;
    }
    std::sort(keys + 0, keys + num_input);
    for (int i = 0; i < num_input; i++)
        printf("%s\n", input[keys[i].second]);
    return 0;
}